<template>
    <el-dialog width="604px" :model-value="modelValue" @closed="handleClose">
        <section class="group_btn">
            <label>导入方式：</label>
            <el-radio-group v-model="type" @change="changeType">
                <el-radio :label="1">按楼盘名称导入</el-radio>
                <el-radio :label="2">按楼盘编码导入</el-radio>
            </el-radio-group>
        </section>
        <section class="switch">
            设置楼盘调度上限，导入后自动调度
            <el-switch
                v-model="status"
                inline-prompt
                style="--el-switch-on-color: #e60044; --el-switch-off-color: #bfbfbf"
                @change="changeSwich"
            />
        </section>
        <el-form-item>
            <el-input v-model="textarea" :rows="10" type="textarea" :placeholder="placeholder" />
        </el-form-item>
        <section class="tip">
            注意：若楼盘名称中存在空格，系统无法导入；若存在这种情况，建议使用楼盘编码进行导入
        </section>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" :loading="submitLoading" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed, reactive, watch } from 'vue';
import { importPremises, exportFailPremises } from '@/api/plan.ts';
import { ElMessage, ElMessageBox } from 'element-plus';
import { exportFormBlob } from '@/utils/common.ts';
import { el } from 'element-plus/lib/locale/index';

const emits = defineEmits<{(e: 'update:modelValue', visible: boolean): void; (e: 'success'): void }>();
let type = ref(1);
let status = ref(false);
const submitLoading = ref(false);
const textarea = ref(null);
const placeholder = ref('示例（按楼盘名称导入）：\r\n布鲁明顿广场A座\r\n布鲁明顿广场B座');
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    planDetail: {
        type: Object,
        default: () => null,
    },
    pointProperty: {
        type: Number,
        default: 0,
    },
});
const handleClose = () => {
    textarea.value = null;
    type.value = 1;
    status.value = false;
    emits('update:modelValue', false);
};

const changeSwich = (val: boolean) => {
    status.value = val;
    if (type.value === 1 && status.value) {
        placeholder.value = '示例（按楼盘名称导入）：\r\n布鲁明顿广场A座 100\r\n布鲁明顿广场B座 200';
    } else if (type.value === 1 && !status.value) {
        placeholder.value = '示例（按楼盘名称导入）：\r\n布鲁明顿广场A座\r\n布鲁明顿广场B座';
    } else if (type.value === 2 && status.value) {
        placeholder.value = '示例（按楼盘编码导入）：\r\n50439095 100\r\n84390984 200';
    } else if (type.value === 2 && !status.value) {
        placeholder.value = '示例（按楼盘编码导入）：\r\n50439095\r\n84390984';
    }
};
const changeType = (val: number) => {
    type.value = val;
    changeSwich(status.value);
};
const submit = async () => {
    const params = {
        planId: props.planDetail.planId,
        premisesList: textarea.value.split(/[\r\n]+/).filter((code) => code),

        autoDispatch: +status.value,
        type: +type.value,
        hasNetwork: props.pointProperty,
    };
    params.premisesList = params.premisesList.map((item: string) => {
        return item.trim();
    });
    console.log('params', params);

    let handleId;
    submitLoading.value = true;

    try {
        let data = await importPremises(params);
        handleId = data?.handleId;
        ElMessageBox.confirm(`成功导入楼盘${data.successNum}个，失败${data.failNum}个`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '下载失败明细',
        })
            .then(() => {
                ElMessage.success('操作成功！');
            })
            .catch(async () => {
                if (handleId) {
                    const { file, fileName } = await exportFailPremises({
                        handleId,
                        autoDispatch: params.autoDispatch,
                    });
                    exportFormBlob(file, fileName);
                } else {
                    ElMessage.error('没有下载失败明细');
                }
            });
    } finally {
        submitLoading.value = false;
    }

    handleClose();
    emits('success');
};
watch(
    () => props.modelValue,
    (newValue) => {
        if (newValue) {
            type.value = 1;
            status.value = false;
            changeSwich(false);
        }
    }
);
</script>

<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 4px;
}
.el-radio-group {
    .el-radio {
        height: auto;
    }
}
.switch {
    margin-bottom: 10px;
}
.group_btn {
    display: flex;
    flex: 1;
    margin-bottom: 10px;
}

.tip {
    font-size: 12px;
    color: #999999;
    margin-top: 16px;
}
</style>
